package com.lab.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lab.pojo.Teacher;
import com.lab.service.TeacherService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Resource
    TeacherService teacherService;
    private Map<String,Object> result=new HashMap<String, Object>();
    /**
     * 查询所有教师信息
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/listByPage")
    @ResponseBody
    public Map<String,Object> listByPage(Integer page, Integer rows){
        //设置分页参数
        page=(page-1)*rows;
        PageHelper.offsetPage(page, rows);
        //查询所有数据
        List<Teacher> list= teacherService.allTeachers();

        //使用PageInfo封装查询结果
        PageInfo<Teacher> pageInfo=new PageInfo<Teacher>(list);
        for(Teacher teacher:list){
            if(teacher.getState().equals("1")){
                teacher.setState("正常");
            }else{
                teacher.setState("停用");
            }
        }
        //从PageInfo对象取出查询结果
        //总记录数
        long total=pageInfo.getTotal();
        //当前页数据列表
        List<Teacher> teacherList=pageInfo.getList();
        result.put("total", total);
        result.put("rows", teacherList);
        return result;
    }

    /**
     * 添加和修改
     * @param teacher
     * @return
     */
    @RequestMapping("/saveTeacher")
    @ResponseBody
    public Map<String,Object> saveStudent(Teacher teacher){
        try {
            teacherService.saveTeacher(teacher);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    /**
     * 数据回显
     * @param tid
     * @return
     */
    @RequestMapping("/findTeacherById")
    @ResponseBody
    public Teacher findUserById(Long tid) {
        Teacher teacher= teacherService.findTeacherById(tid);
        return teacher;
    }

    /**
     *删除数据
     * @param tid
     * @return
     */
    @RequestMapping("/deleteTeacher")
    @ResponseBody
    public Map<String,Object> delete(Long[] tid){
        try {
            teacherService.deleteTeacher(tid);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return result;
    }

}
